package com.kexilo.system.service.impl;

import com.kexilo.core.common.constant.Constants;
import com.kexilo.core.common.constant.UserConstants;
import com.kexilo.core.common.core.domain.TreeSelect;
import com.kexilo.core.common.utils.SecurityUtils;
import com.kexilo.core.common.utils.StringUtils;
import com.kexilo.core.role.domain.SysMenu;
import com.kexilo.core.role.domain.SysRole;
import com.kexilo.core.shared.dto.TreeNodeDTO;
import com.kexilo.core.user.domain.SysUser;
import com.kexilo.system.system.mapper.SysMenuMapper;
import com.kexilo.system.system.mapper.SysRoleMenuMapper;
import com.kexilo.system.system.service.ISysMenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单 业务层处理
 * 
 * @author Kexilo
 */
@Service
public class SysMenuServiceImpl implements ISysMenuService {
    
    private static final Logger log = LoggerFactory.getLogger(SysMenuServiceImpl.class);
    
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";
    
    @Autowired
    private SysMenuMapper menuMapper;
    
    @Autowired
    private SysRoleMenuMapper roleMenuMapper;
    
    /**
     * 查询菜单集合
     * 
     * @param userId 用户ID
     * @return 所有菜单信息
     */
    @Override
    public List<SysMenu> selectMenuList(Long userId) {
        return selectMenuList(new SysMenu(), userId);
    }
    
    /**
     * 查询菜单集合
     * 
     * @param menu 菜单信息
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuList(SysMenu menu) {
        return selectMenuList(menu, SecurityUtils.getUserId());
    }
    
    /**
     * 查询菜单集合
     * 
     * @param menu 菜单信息
     * @param userId 用户ID
     * @return 菜单列表
     */
    public List<SysMenu> selectMenuList(SysMenu menu, Long userId) {
        List<SysMenu> menuList = null;
        // 管理员显示所有菜单信息
        if (SysUser.isAdmin(userId)) {
            menuList = menuMapper.selectMenuList(menu);
        } else {
            menu.getParams().put("userId", userId);
            menuList = menuMapper.selectMenuList(menu);
        }
        return menuList;
    }
    
    /**
     * 根据用户查询系统菜单列表
     * 
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    @Cacheable(value = "menu:user", key = "#userId", condition = "#userId != null && #userId > 0")
    public List<SysMenu> selectMenuListByUserId(Long userId) {
        return selectMenuTreeByUserId(userId);
    }
    
    /**
     * 根据用户ID查询权限
     * 
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    @Cacheable(value = "menu:permissions", key = "#userId", condition = "#userId != null && #userId > 0")
    public Set<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = menuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }
    
    /**
     * 根据角色ID查询权限
     * 
     * @param roleId 角色ID
     * @return 权限列表
     */
    @Override
    @Cacheable(value = "menu:role:permissions", key = "#roleId", condition = "#roleId != null && #roleId > 0")
    public Set<String> selectMenuPermsByRoleId(Long roleId) {
        List<String> perms = menuMapper.selectMenuPermsByRoleId(roleId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }
    
    /**
     * 根据用户ID查询菜单树信息
     * 
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    @Cacheable(value = "menu:tree", key = "#userId", condition = "#userId != null && #userId > 0")
    public List<SysMenu> selectMenuTreeByUserId(Long userId) {
        List<SysMenu> menus = null;
        if (SecurityUtils.isAdmin(userId)) {
            menus = menuMapper.selectMenuTreeByUserId(null);
        } else {
            menus = menuMapper.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }
    
    /**
     * 根据角色ID查询菜单树信息
     * 
     * @param roleId 角色ID
     * @return 选中菜单列表
     */
    @Override
    public List<Long> selectMenuListByRoleId(Long roleId) {
        SysRole role = new SysRole();
        role.setRoleId(roleId);
        return menuMapper.selectMenuListByRoleId(roleId, role.getMenuCheckStrictly());
    }
    
    /**
     * 构建前端路由所需要的菜单
     * 
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<Object> buildMenus(List<SysMenu> menus) {
        List<Object> routers = new LinkedList<Object>();
        for (SysMenu menu : menus) {
            Map<String, Object> router = new LinkedHashMap<String, Object>();
            router.put("hidden", "1".equals(menu.getVisible()));
            router.put("name", getRouteName(menu));
            router.put("path", getRouterPath(menu));
            router.put("component", getComponent(menu));
            router.put("query", menu.getQuery());
            Map<String, Object> meta = new LinkedHashMap<String, Object>();
            meta.put("title", menu.getMenuName());
            meta.put("icon", menu.getIcon());
            meta.put("noCache", "1".equals(menu.getIsCache()));
            meta.put("link", isMenuFrame(menu) ? menu.getPath() : null);
            router.put("meta", meta);
            List<SysMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.put("alwaysShow", true);
                router.put("redirect", "noRedirect");
                router.put("children", buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.put("meta", meta);
                List<Object> childrenList = new ArrayList<Object>();
                Map<String, Object> children = new LinkedHashMap<String, Object>();
                children.put("path", menu.getPath());
                children.put("component", menu.getComponent());
                children.put("name", StringUtils.capitalize(menu.getPath()));
                children.put("meta", new LinkedHashMap<String, Object>() {{
                    put("title", menu.getMenuName());
                    put("icon", menu.getIcon());
                    put("noCache", "1".equals(menu.getIsCache()));
                    put("link", menu.getPath());
                }});
                childrenList.add(children);
                router.put("children", childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.put("meta", meta);
                router.put("path", "/");
                List<Object> childrenList = new ArrayList<Object>();
                Map<String, Object> children = new LinkedHashMap<String, Object>();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.put("path", routerPath);
                children.put("component", UserConstants.INNER_LINK);
                children.put("name", StringUtils.capitalize(routerPath));
                children.put("meta", new LinkedHashMap<String, Object>() {{
                    put("title", menu.getMenuName());
                    put("icon", menu.getIcon());
                    put("link", menu.getPath());
                }});
                childrenList.add(children);
                router.put("children", childrenList);
            }
            routers.add(router);
        }
        return routers;
    }
    
    /**
     * 构建前端所需要树结构
     * 
     * @param menus 菜单列表
     * @return 树结构列表
     */
    @Override
    public List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysMenu dept : menus) {
            tempList.add(dept.getMenuId());
        }
        for (SysMenu menu : menus) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }
    
    /**
     * 构建前端所需要下拉树结构
     * 
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    @Override
    public List<Object> buildMenuTreeSelect(List<SysMenu> menus) {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream()
                .map(this::convertMenuToTreeNode)
                .map(TreeSelect::new)
                .collect(Collectors.toList());
    }
    
    /**
     * 将菜单实体转换为树形节点DTO
     * 
     * @param menu 菜单实体
     * @return 树形节点DTO
     */
    private TreeNodeDTO convertMenuToTreeNode(SysMenu menu) {
        TreeNodeDTO node = new TreeNodeDTO();
        node.setId(menu.getMenuId());
        node.setLabel(menu.getMenuName());
        node.setParentId(menu.getParentId() != null ? menu.getParentId() : 0L);
        
        // 递归转换子节点
        if (menu.getChildren() != null && !menu.getChildren().isEmpty()) {
            List<TreeNodeDTO> childNodes = menu.getChildren().stream()
                    .map(this::convertMenuToTreeNode)
                    .collect(Collectors.toList());
            node.setChildren(childNodes);
        }
        
        return node;
    }
    
    /**
     * 根据菜单ID查询信息
     * 
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    @Override
    @Cacheable(value = "menu:info", key = "#menuId", condition = "#menuId != null && #menuId > 0")
    public SysMenu selectMenuById(Long menuId) {
        return menuMapper.selectMenuById(menuId);
    }
    
    /**
     * 是否存在菜单子节点
     * 
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean hasChildByMenuId(Long menuId) {
        int result = menuMapper.hasChildByMenuId(menuId);
        return result > 0;
    }
    
    /**
     * 查询菜单使用数量
     * 
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean checkMenuExistRole(Long menuId) {
        int result = roleMenuMapper.checkMenuExistRole(menuId);
        return result > 0;
    }
    
    /**
     * 新增保存菜单信息
     * 
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    @CacheEvict(value = {"menu:tree", "menu:user", "menu:permissions", "menu:role:permissions", "menu:info"}, allEntries = true)
    public int insertMenu(SysMenu menu) {
        return menuMapper.insertMenu(menu);
    }
    
    /**
     * 修改保存菜单信息
     * 
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    @CacheEvict(value = {"menu:tree", "menu:user", "menu:permissions", "menu:role:permissions", "menu:info"}, allEntries = true)
    public int updateMenu(SysMenu menu) {
        return menuMapper.updateMenu(menu);
    }
    
    /**
     * 删除菜单管理信息
     * 
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    @CacheEvict(value = {"menu:tree", "menu:user", "menu:permissions", "menu:role:permissions", "menu:info"}, allEntries = true)
    public int deleteMenuById(Long menuId) {
        return menuMapper.deleteMenuById(menuId);
    }
    
    /**
     * 校验菜单名称是否唯一
     * 
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public boolean checkMenuNameUnique(SysMenu menu) {
        Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
        SysMenu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId(), menuId);
        if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) {
            return false; // NOT_UNIQUE
        }
        return true; // UNIQUE
    }
    
    /**
     * 获取路由名称
     * 
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }
    
    /**
     * 获取路由地址
     * 
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }
    
    /**
     * 获取组件信息
     * 
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }
    
    /**
     * 是否为菜单内部跳转
     * 
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenu menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }
    
    /**
     * 是否为内链组件
     * 
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenu menu) {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }
    
    /**
     * 是否为parent_view组件
     * 
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenu menu) {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }
    
    /**
     * 根据父节点的ID获取所有子节点
     * 
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iter = list.iterator(); iter.hasNext();) {
            SysMenu t = (SysMenu) iter.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }
    
    /**
     * 递归列表
     * 
     * @param list
     * @param t
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }
    
    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext()) {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }
    
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0;
    }
    
    /**
     * 内链域名特殊字符替换
     */
    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[] { Constants.HTTP, Constants.HTTPS, Constants.WWW, ".", ":" },
                new String[] { "", "", "", "/", "/" });
    }
}
